var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');


var PORT=3000;
app.listen(PORT);

var clientCount=0;

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.on('connection',function(socket){
    clientCount++;
    socket.nickname='user'+clientCount;
    //广播
    io.emit('enter',socket.nickname+'comes in');

    //发送
    socket.on('message',function(str){
        console.log(socket.nickname+' says:'+str);
        io.emit('message',socket.nickname+' says:'+str)
    })

    //客户端断开
    socket.on('disconnect',function(){
      io.emit('leave',socket.nickname+'left')
    })

});